﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using WINBASE.Controls;
using System.Reflection;
using System.IO;
using System.Drawing;

namespace WINBASE
{
    public partial class frmFmmn : DockContent
    {
        #region Declaration

        ToolStripItem[] tsiMenu;
        TreeNode[] trnNodes; 

        #endregion

        #region Constructor & Load

        public frmFmmn()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            InitializeData();
            InitializeUI();
        }

        #endregion

        #region Events

        private void trvNodes_GotFocus(object sender, EventArgs e)
        {
            if (drSelectedNode != null && drSelectedNode["ParentTrxNo"] != DBNull.Value && (string)drSelectedNode["ViewFrmName"] != "")
            {
                ApplicationObject.FrmMain.dpnlMain.Contents[0].DockHandler.GiveUpFocus();
            }
        }

        private void tspModule_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.GetType() == typeof(WLCModToolStrip))
            {
                this.Text = e.ClickedItem.Text;
                foreach (ToolStripItem tspbtnModule in tspModule.Items)
                {
                    if (tspbtnModule.GetType() == typeof(WLCModToolStrip))
                    {
                        ((WLCModToolStrip)tspbtnModule).Checked = false;
                    }
                }
                ((WLCModToolStrip)e.ClickedItem).Checked = true;

                drSelectedMenu = ApplicationData.DtModule.Rows
                                .Cast<DataRow>()
                                .Where(x =>
                                    (int)x["TrxNo"] == (int)((WLCModToolStrip)e.ClickedItem).ControlId).Single();

                InitNodes((int)this.SelectedMenu["TrxNo"]);
                if (trvNodes.Nodes.Count > 0)
                {
                    trvNodes.SelectedNode = trvNodes.Nodes[0];
                    trvNodes.Focus();
                }

                trvNodes.ExpandAll();
            }
        }

        private void trvNodes_AfterSelect(object sender, TreeViewEventArgs e)
        {
            drSelectedNode = ApplicationData.DtNodes.Rows
                             .Cast<DataRow>()
                             .Where(x =>
                                 (int)x["TrxNo"] == (int)((WLCTreeNode)e.Node).ControlId).SingleOrDefault();

            if (drSelectedNode != null && (string)drSelectedNode["ViewFrmName"] != "")
            {
                ShowViewForm();
            }
        }

        #endregion

        #region Methods

        public void InitializeData()
        {
        }

        public void InitializeUI()
        {
            ApplicationObject.Forms = new List<WLCMainForm>();
            InitMenu();
            this.trvNodes.GotFocus += trvNodes_GotFocus;

            if (tspModule.Items.Count >= 2)
            {
                tspModule_ItemClicked(null, new ToolStripItemClickedEventArgs(tsiMenu[0]));
            }
        }

        public void InitMenu()
        {
            tsiMenu = new ToolStripItem[ApplicationData.DtModule.Rows.Count];
            int i = 0;
            foreach (DataRow drMenu in ApplicationData.dtMenu.Rows)
            {
                tsiMenu[i] = new WLCModToolStrip((int)drMenu["TrxNo"], "tsp" + (string)drMenu["ModuleCode"], (string)drMenu["ModuleName"]);

                if (drMenu["ModuleImg"] != DBNull.Value)
                {
                    byte[] photo_aray = (byte[])drMenu["ModuleImg"];
                    MemoryStream ms = new MemoryStream(photo_aray);
                    Image ModuleImg = new Bitmap(Image.FromStream(ms), new Size(24,24));
                    tsiMenu[i].Image = ModuleImg;
                }
                i++;
            }
            tspModule.Items.AddRange(tsiMenu);
        }

        public void InitNodes(int ModuleTrxNo)
        {
            trvNodes.Nodes.Clear();

            var drParentRows = ApplicationData.DtNodes.Rows
                              .Cast<DataRow>()
                              .Where(x =>
                                  x["ParentTrxNo"] == DBNull.Value &&
                                  (int)x["ModuleTrxNo"] == ModuleTrxNo).ToList();
            trnNodes = new TreeNode[drParentRows.Count];
            int i = 0;
            foreach (DataRow drNode in drParentRows)
            {
                trnNodes[i] = new WLCTreeNode((int)drNode["TrxNo"], "trn" + (string)drNode["NodeName"], (string)drNode["NodeDescription"]);
                addChildNodes(trnNodes[i], (int)drNode["TrxNo"]);
                i++;
            }

            if (trnNodes.Count() > 0) trvNodes.Nodes.AddRange(trnNodes);
        }

        public void ShowViewForm()
        {
            try
            {
                Type typSelectBaseFormName = Type.GetType((string)SelectedNode["ViewBaseFrmKey"]);
                string strSelectFormName = (string)ApplicationObject.FrmModuleList.SelectedNode["ViewBaseFrmKey"];

                WLCMainForm myForm = ApplicationObject.Forms.SingleOrDefault(x => x.BaseControlName == strSelectFormName);
                if (myForm == null)
                {
                    myForm = (WLCMainForm)Activator.CreateInstance(typSelectBaseFormName);
                    ApplicationObject.Forms.Add(myForm);
                }
                else if (myForm.IsDisposed) myForm = (WLCMainForm)Activator.CreateInstance(typSelectBaseFormName);

                myForm.InitializeBaseData();
                myForm.InitializeData();
                myForm.DockHandler.DockPanel = ApplicationObject.FrmMain.dpnlMain;
                myForm.DockHandler.DockAreas = WeifenLuo.WinFormsUI.Docking.DockAreas.Document;
                myForm.Activate();

                ApplicationObject.FrmMain.dpnlMain_ActiveDocumentChanged(null,null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void ShowDetailForm(DataRowView dr)
        {
            if (ApplicationObject.FrmModuleList.SelectedNode["DetailBaseFrmKey"] != DBNull.Value)
            {
                try
                {
                    Type typSelectBaseFormName = Type.GetType(((string)ApplicationObject.FrmModuleList.SelectedNode["DetailBaseFrmKey"]));
                    string strSelectFormName = (string)ApplicationObject.FrmModuleList.SelectedNode["DetailFrmKey"];

                    WLCDetailForm myForm = (WLCDetailForm)Activator.CreateInstance(typSelectBaseFormName);
                    myForm.InitializeBaseData();
                    myForm.InitializeData(dr);
                    
                    myForm.DockHandler.DockPanel = ApplicationObject.FrmMain.dpnlMain;
                    myForm.DockHandler.DockAreas = WeifenLuo.WinFormsUI.Docking.DockAreas.Document;
                    myForm.Activate();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public bool DeleteDetail(DataRowView dr)
        {
            if (ApplicationObject.FrmModuleList.SelectedNode["DetailBaseFrmKey"] != DBNull.Value)
            {
                try
                {
                    Type typSelectBaseFormName = Type.GetType(((string)ApplicationObject.FrmModuleList.SelectedNode["DetailBaseFrmKey"]));
                    string strSelectFormName = (string)ApplicationObject.FrmModuleList.SelectedNode["DetailFrmKey"];

                    WLCDetailForm myForm = (WLCDetailForm)Activator.CreateInstance(typSelectBaseFormName);
                    myForm.InitializeBaseData();
                    myForm.InitializeData(dr);
                    return myForm.DeleteData(dr);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            else return false;
        }

        public TreeNode addChildNodes(TreeNode ParentNode, int ParentTrxNo)
        {
            var drChildRow = ApplicationData.DtNodes.Rows
                            .Cast<DataRow>()
                            .Where(x =>
                                x["ParentTrxNo"] != DBNull.Value &&
                                (int)x["ParentTrxNo"] == ParentTrxNo).ToList();
            int i = 0;
            foreach (DataRow drNode in drChildRow)
            {
                TreeNode ChildNode = new WLCTreeNode((int)drNode["Trx No"], "trn" + (string)drNode["NodeName"], (string)drNode["NodeDescription"]);
                ParentNode.Nodes.Add(ChildNode);

                var drSubChildRow = ApplicationData.DtNodes.Rows
                            .Cast<DataRow>()
                            .Where(x =>
                                x["ParentTrxNo"] != DBNull.Value &&
                                (int)x["ParentTrxNo"] == (int)drNode["TrxNo"]).ToList();
                if (drSubChildRow.Count > 0) addChildNodes(ChildNode, (int)drNode["ParentTrxNo"]);
                i++;
            }
            return ParentNode;
        }

        #endregion

        #region Property

        DataRow drSelectedMenu;
        public DataRow SelectedMenu
        {
            get { return drSelectedMenu; }
        }

        DataRow drSelectedNode;
        public DataRow SelectedNode
        {
            get { return drSelectedNode; }
        }

        

        #endregion
    }
}